#include "NotificationCenter.h"
#include <algorithm>

NotificationCenter &NotificationCenter::get()
{
    static NotificationCenter _instance;
    return _instance;
}

bool NotificationCenter::addObserver(const QString &nameId,const NotifyInterface & t)
{
    std::lock_guard<std::mutex> lock(m_lock);

    auto it = m_objs.find(nameId);
    if (it == m_objs.end()) {
        std::list<NotifyInterface> objs{t};
        m_objs.insert(nameId,objs);
    } else {
        std::list<NotifyInterface> &objs = it.value();
        if (find(objs.begin(),objs.end(),t) != objs.end()) {
            return false;
        }
        objs.push_back(t);
    }
    return true;
}

bool NotificationCenter::removeObserver(const QString &nameId, const NotifyInterface &t)
{
    std::lock_guard<std::mutex> lock(m_lock);

    auto it = m_objs.find(nameId);
    if (it != m_objs.end()) {
        auto objs = it.value();
        auto findIt = find(objs.begin(),objs.end(),t);
        if (findIt == objs.end())
            return false;

        objs.erase(findIt);

        if (objs.size() == 0) {
            m_objs.remove(nameId);
        }
        return true;
    } else {
        return false;
    }
}

bool NotificationCenter::removeObserver(const NotifyInterface &t)
{
    std::lock_guard<std::mutex> lock(m_lock);

    for (auto it = m_objs.begin(); it != m_objs.end();) {
        auto findIt = find(it.value().begin(),it.value().end(),t);
        if (findIt != it.value().end()) {
            it.value().remove(t);
            if (it.value().size() == 0) {
                it = m_objs.erase(it);
                continue;
            } else {
                it++;
            }
        }
    }

    return true;
}

void NotificationCenter::postNofication(const QString &name,const QByteArray &)
{

}
